﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 商品应用服务类
    /// </summary>
    public class ProductAppService : ApplicationService, IProductAppService
    {
        private readonly IRepository<Product, int> _productRepository;

        public ProductAppService(
            IRepository<Product, int> productRepository)
        {
            _productRepository = productRepository;
        }

        // 分页列表
        public async Task<ListResponse<ProductDto>> PagedListAsync(
            PagedListRequest request, 
            string description, 
            string name)
        {
            // 数据筛选
            var query = await _productRepository.GetQueryableAsync();
            query = query.WhereIf(!string.IsNullOrWhiteSpace(description), m => m.Description.Contains(description));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(name), m => m.Name.Contains(name));
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Product>, List<ProductDto>>(list);
            return ListResponse<ProductDto>.Successful(count, dtos);
        }
    }
}